// pages/confirm/confirm.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isCart: 0,
    userInfo: {
      receiver: '',
      tel: ''
    },
    leader: {
      leader_name: '',
      address: ''
    },
    cartIds: [],
    product: [],
    totalPrice: 0.00
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this,
      goods = JSON.parse(options.goods)
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    if (options.is_cart) {
      that.setData({
        isCart: 1,
        cartIds: options.cart_ids,
        product: goods
      })
    } else {
      that.setData({
        product: goods
      })
    }
    that.getTotalPrice(that.data.product)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getOrderInfo(this.data.isCart)
  },

  getOrderInfo(is_cart) {
    let that = this,
      data
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      if (is_cart == 1) {
        wx.request({
          url: app.globalData.hostAPI + '/api/v1/cart/create-order?access_token=' + accessToken,
          success: res => {
            data = res.data.data
            if (res.data.status === 1) {
              that.setData({
                'leader.leader_name': data.leader_name,
                'leader.address': data.address,
                'userInfo.receiver': data.contact_name,
                'userInfo.tel': data.contact_phone,
              })
              wx.hideLoading()
            } else if(res.data.status == -20) {
              wx.showModal({
                showCancel: false,
                title: '提示',
                content: '购物车内有无效产品',
                success: res => {
                  if(res.confirm) {
                    wx.switchTab({
                      url: '../cart/cart',
                    })
                  }
                }
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: res.data.msg
              })
            }
          },
          fail: res => {
            wx.showToast({
              icon: 'none',
              title: res.data.msg
            })
          }
        })
      } else {
        wx.request({
          url: app.globalData.hostAPI + '/api/v1/order/create?access_token=' + accessToken,
          success: res => {
            data = res.data.data
            if (res.data.status === 1) {
              that.setData({
                'leader.leader_name': data.leader_name,
                'leader.address': data.address,
                'userInfo.receiver': data.contact_name,
                'userInfo.tel': data.contact_phone,
              })
              wx.hideLoading()
            } else if(res.data.status == -10) {
              wx.hideLoading()
              wx.showModal({
                showCancel: false,
                title: '提示',
                content: '请选择团长',
                success: res => {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '../community/community',
                    })
                  }
                }
              })
              
            } else {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: res.data.msg
              })
            }
          }
        })
      }
    })
  },

  /**
   * 下单按钮
   */

  confirm: function() {
    let that = this,
      isCart = that.data.isCart,
      userInfo = that.data.userInfo,
      telReg = /^1(3|4|5|7|8)\d{9}$/
    if (userInfo.receiver === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入昵称',
      })
      return false
    }

    if (userInfo.tel === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入电话',
      })
      return false
    }

    if (!telReg.test(userInfo.tel)) {
      wx.showToast({
        icon: 'none',
        title: '号码不正确',
      })
      return false
    }

    if (isCart == 1) {
      that.cartOrder()
    } else {
      that.createOrder()
    }
  },

  createOrder: function() {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/api/v1/order/create?access_token=' + accessToken,
        method: 'POST',
        header: {
          "Content-type": "application/x-www-form-urlencoded"
        },
        data: {
          receiver: that.data.userInfo.receiver,
          tel: that.data.userInfo.tel,
          goods_id: that.data.product[0].goods_id,
          num: that.data.product[0].number
        },
        success: res => {
          if (res.data.status === 1) {
            wx.request({
              url: app.globalData.hostAPI + '/api/v1/wxpay/unified-order?access_token=' + accessToken + '&order_sn=' + res.data.data.order_sn,
              success: res => {
                if (res.data.status === 1) {
                  wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    package: res.data.data.package,
                    signType: 'MD5',
                    paySign: res.data.data.paySign,
                    success: res => {
                      wx.hideLoading()
                      wx.showToast({
                        icon: 'none',
                        title: '购买成功',
                      })
                      wx.navigateTo({
                        url: '../order/order',
                      })
                    },
                    fail: err => {
                      wx.hideLoading()
                      wx.showToast({
                        icon: 'none',
                        title: '交易取消',
                      })
                      wx.navigateTo({
                        url: '../order/order',
                      })
                    }
                  })
                }
              }
            })
          }
        }
      })
    })
  },

  cartOrder: function() {
    let that = this,
      ids = JSON.stringify([that.data.cartIds])
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/api/v1/cart/create-order?access_token=' + accessToken,
        method: 'POST',
        header: {
          "Content-type": "application/x-www-form-urlencoded"
        },
        data: {
          cart_ids: that.data.cartIds,
          receiver: that.data.userInfo.receiver,
          tel: that.data.userInfo.tel
        },
        success: res => {
          if (res.data.status === 1) {
            wx.request({
              url: app.globalData.hostAPI + '/api/v1/wxpay/unified-order?access_token=' + accessToken + '&order_sn=' + res.data.data.order_sn,
              success: res => {
                if (res.data.status === 1) {
                  wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    package: res.data.data.package,
                    signType: 'MD5',
                    paySign: res.data.data.paySign,
                    success: res => {
                      wx.hideLoading()
                      if (res.errMsg === 'requestPayment:ok') {
                        wx.showToast({
                          icon: 'success',
                          title: '支付成功',
                          success: res => {
                            wx.navigateTo({
                              url: '../order/order',
                            })
                          }
                        })
                      } else {
                        wx.showToast({
                          icon: 'none',
                          title: '支付失败',
                          success: res => {
                            wx.navigateTo({
                              url: '../order/order',
                            })
                          }
                        })
                      }
                    },
                    fail: err => {
                      wx.showToast({
                        icon: 'none',
                        title: '交易取消',
                        success: res => {
                          wx.navigateTo({
                            url: '../order/order',
                          })
                        }
                      })
                    }
                  })
                }
              }
            })
          }
        }
      })
    })
  },

  /**
   * input value
   */
  nameValue: function(e) {
    console.log(e)
    this.setData({
      'userInfo.receiver': e.detail.value
    })
  },

  phoneValue: function(e) {
    this.setData({
      'userInfo.tel': e.detail.value
    })
  },

  /**
   * total
   */
  getTotalPrice: function(proList) {
    let that = this,
      totalPrice = 0.00,
      k
    for (k in proList) {
      totalPrice += parseFloat(proList[k].discount_price) * proList[k].number
    }
    that.setData({
      totalPrice: totalPrice.toFixed(2)
    })
  }
})